// pages/changepassword/changepassword.js
const http = require('../../utils/http.js');
Page({
  data: {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  },

  handleOldPasswordInput: function(e) {
    this.setData({
      oldPassword: e.detail.value
    });
  },

  handleNewPasswordInput: function(e) {
    this.setData({
      newPassword: e.detail.value
    });
  },

  handleConfirmPasswordInput: function(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  updatePassword: function() {
    // 验证是否输入完整信息
    if (!this.data.oldPassword || !this.data.newPassword || !this.data.confirmPassword) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }
    // 验证两次密码是否一致
    if (this.data.newPassword !== this.data.confirmPassword) {
      wx.showToast({
        title: '新旧密码不一致',
        icon: 'none'
      });
      return;
    }
    const StorageUserInfo = wx.getStorageSync('userInfo') || {};
    const oldPassword = StorageUserInfo.password;
    // 验证新旧密码是否一致
    if(oldPassword !== this.data.oldPassword ){
      console.log("this in change password");
      console.log(oldPassword);
      wx.showToast({
        title: '旧密码不正确',
        icon: 'none'
      });
      return;
    }
    // 发送请求
    const url = '/app/user/api/resetPwd';
    const postData = {
      userId: StorageUserInfo.userId, //用户ID
      password: this.data.newPassword, //密码
      updateBy: StorageUserInfo.appName //当前app的名称，例如：内大考研
    };
    http.post(url,postData).then(res =>{
      if(res.data.code == 200){
        // 处理更新密码逻辑
        wx.showToast({
          title: '密码更新成功',
          icon: 'none'
        });
        StorageUserInfo.password = this.data.newPassword;

        // 使用同步方法储存
        try {
          wx.setStorageSync('userInfo', StorageUserInfo);
          console.log('更新本地用户信息成功');
          console.log(StorageUserInfo);
          wx.showToast({
            title: '密码修改成功，现返回主页',
            icon: 'none',
            duration: 2000
          });
        } catch(e) {
          console.error('更新本地用户信息失败', e);
          wx.showToast({
            title: '密码本地储存失败，现返回主页',
            icon: 'none',
            duration: 2000
          });
        } finally{
          // 跳转页面
          wx.switchTab({
            url: '/pages/mine/mine'
          });
        }
      } else {
        console.log("GET请求发送成功，结果出错");
        wx.showToast({
          title: '未知错误',
          icon: 'none',
          duration: 2000
        });
      }
    }).catch(err => {
      console.log('GET请求发送失败');
      console.log(err);
      wx.showToast({
        title: '系统错误，请稍后重试',
        icon: 'none',
        duration: 2000
      });
    })
    
  }
});
